package com.rykj.qxj.apiService.service.impl;

import apiRedis.DynamicCacheGet;
import apiRedis.DynamicCacheHash;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.github.pagehelper.PageInfo;
import com.rykj.qxj.apiService.exception.*;
import com.rykj.qxj.apiService.service.IDataApiService;
import com.rykj.qxj.result.BaseResponse;
import com.rykj.qxj.server.common.constants.ApiRequestModeStatusEnum;
import com.rykj.qxj.server.common.constants.ApiStatusEnum;
import com.rykj.qxj.server.common.constants.ApiVerifyStatusEnum;
import com.rykj.qxj.server.common.constants.DeleteStatusEnum;
import com.rykj.qxj.server.model.em.RedisComdType;
import com.rykj.qxj.server.model.entity.*;
import com.rykj.qxj.server.services.*;
import com.rykj.qxj.server.util.date.DateUtils;
import com.rykj.qxj.server.util.object.StringUtils;
import com.rykj.qxj.util.NamedParameterJdbcTemplateUtil;
import com.rykj.qxj.util.Page;
import com.rykj.qxj.util.SignUtil;
import com.rykj.qxj.util.SqlTemplateUtils;
import com.rykj.qxj.util.net.HttpClientUtils;
import com.techindata.cacheredis.CacheGet;
import com.techindata.cacheredis.CachePut;
import lombok.extern.log4j.Log4j;
import org.apache.commons.text.StrSubstitutor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.*;
import org.springframework.jdbc.core.namedparam.NamedParameterJdbcTemplate;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

import javax.servlet.ServletRequest;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.util.*;

@Log4j
@Service
public class DataApiServiceImpl implements IDataApiService {
	@Autowired
	private IApiManageService apiManageService;
	
	@Autowired
	private IApiVersionManageService apiVersionManageService;
	
	@Autowired
	private IDatabaseSourceService databaseSourceService;
	
	@Autowired
	private IApiRequestParamService apiRequestParamService;
	
	@Autowired
	private IApiResponseParamService apiResponseParamService;
	
	@Autowired
	private IUpdateFieldService updateFieldService;
	
	@Autowired
	private IAddFieldService addFieldService;
	
	@Autowired
	private IApplyManageService applyManageService;
	
	@Autowired
	private ISystemParameterService systemParameterService;
	@Value("${pageNo}")
	private Integer pageNo;
	@Value("${pageSize}")
	private Integer pageSize;
 	
	private static final String REQUEST_METHOD_GET = "GET";  //GET 请求
	private static final String REQUEST_METHOD_POST = "post"; //POST请求
	private static final String REQUEST_METHOD_PUT = "put";    //PUT请求
	private static final String REQUEST_METHOD_DELETE = "delete";  //DELETE请求
	
	private static final String BUSINESS="business";  //业务库
	private static final String SUBJECT="subject";  //主题库
	
	private static final String  REGEXP = "\'";  //替换sql语句中的单引号表达式
	//单个接口的QPS
	private static final String SINGL_QUERIES_PER_SECOND="singlQueriesPerSecond";
	//全局所有接口的QPS
	private static final String GLOBAL_QUERIES_PER_SECOND="globalQueriesPerSecond";
	
	private static final String REQUEST_API_SERVICE_URL="request:api:service:url";
	public BaseResponse doPostService(HttpServletRequest request,HttpServletResponse response) throws AppKeyIsNotNullException, DoAuthenticationFailException,RequestParamIsNotMatchException,DatabaseSourceIsNullException, ApplyIsNotOnException, RequestURIErrorException, ApiIsDisableException, ApiIsDeleteException, ApiVersionIsDisableException, ApiVersionIsNotVerifyPassException, ApiVersionIsDeleteException {
		BaseResponse responseResult=null;
		String appKey=request.getHeader("appKey");
		if(StringUtils.isEmpty(appKey)){
			appKey=  request.getParameter("appKey");
		}
		if(StringUtils.isBlank(appKey)) {
			throw new AppKeyIsNotNullException("接口应用的appKey不能为空!");
		}
		if(log.isInfoEnabled()) {
			log.info("appKey="+appKey);
		}
		if(!doCheckingApplyIsOn(appKey)) {
			throw new ApplyIsNotOnException("当前appKey对应的应用还未上线!");
		}
		
		//ApiManage apiManage = apiManageService.selectApiManageAndApiversionIdByApiIdAndVersionStatusAndVerifyStatusAndDeleteStatus(request.getRequestURI().replace("/weather-api", ""));
		ApiManage apiManage = getApiManage(request.getRequestURI().replace("/weather-api", ""),request.getMethod());
		if(doAuthentication(request,response,appKey)) {
			//做认证成功以后的操作
			Map<String, Object> resMap=null;
		    //业务库中的插入操作   以流的方式传递 在验证的时候读取过一次，现在继续读取就没有数据了
			//String requestBodyJsonStr = getRequestBodyStr(request);
			String requestBodyJsonStr=(String) request.getAttribute("requestBodyJsonStr");
			//将requestBody中请求字符串转化为map
			 resMap = SignUtil.convertJsonToMap(requestBodyJsonStr);
			// 去掉签名信息
			 resMap.remove("sign");
			 List<AddField> addFieldList = addFieldService.selectAddFieldListByApiVersionId(apiManage.getApiVersionId());
			 Set<String> addFieldPenNameSet=new HashSet<String>();
			 if(addFieldList!=null) {
				 for (AddField addField : addFieldList) {
					 addFieldPenNameSet.add(addField.getPenName());
				}
				 
			 }
			 Set<String> requestKey = resMap.keySet();
			 if(isSetEqual(addFieldPenNameSet, requestKey)) {
				 DatabaseSource databaseSource = databaseSourceService.getDatabaseSourceDetails(apiManage.getDatabaseSourceId());
				 if(databaseSource==null) {
					 throw new DatabaseSourceIsNullException("接口的数据源为空，请检查配置!");
				 }
				 log.info("数据库中存储的sql:"+apiManage.getSqlTemplet());
				 NamedParameterJdbcTemplate namedParameterJdbcTemplate = NamedParameterJdbcTemplateUtil.getNamedParameterJdbcTemplate(databaseSource.getDatabaseIP(), databaseSource.getPort(), databaseSource.getDatabaseName(), databaseSource.getUserName(), databaseSource.getPassword());
				 int update = namedParameterJdbcTemplate.update(apiManage.getSqlTemplet().replaceAll(REGEXP, ""), resMap);
				 if(update!=0) {
					 log.info("插入成功!");
					 responseResult=new BaseResponse("200","插入成功",null);
				 }
			 }else {
				 log.info("请求参数不匹配,请更正以后再访问!");
				 throw new RequestParamIsNotMatchException("请求参数不匹配,请更正以后再访问!");
			 }
		}else {
			log.info("认证失败!请检查参数名称或者appKey是否正确");
			throw new DoAuthenticationFailException("认证失败!请检查参数名称或者appKey是否正确!");
			
		}
		return responseResult;
	}
	
	public PageInfo doGetService(HttpServletRequest request,HttpServletResponse response) throws Exception {
		PageInfo page=null;
		String appKey=request.getHeader("appKey");
		if(StringUtils.isEmpty(appKey)){
			appKey= request.getParameter("appKey");
		}
		if(StringUtils.isBlank(appKey)) {
			throw new AppKeyIsNotNullException("接口应用的appKey不能为空!");
		}
		if(log.isInfoEnabled()) {
			log.info("appKey="+appKey);
		}
		if(!doCheckingApplyIsOn(appKey)) {
			throw new ApplyIsNotOnException("当前appKey对应的应用还未上线,请联系后台管理员...");
		}
		ApiManage apiManage = getApiManage(request.getRequestURI().replace("/weather-api", ""),request.getMethod());
		if(doAuthentication(request,response,appKey)) {
			//验证成功
			 if(apiManage.getApiType().equals(SUBJECT)) {
	    		 //主题库中的第三方接口
	    		 if(apiManage.getIsOutSide().equals(ApiRequestModeStatusEnum.YES.getStatus())) {
	    			 //doSubjectOutSideByGet(request,apiManage,response);
	    		 }else {
	    			 page= doSubjectByGet(request,apiManage,response);
	    		 }
	    		 //业务库
	    	 }else {
	    		
	    		 if(apiManage.getIsOutSide().equals(ApiRequestModeStatusEnum.YES.getStatus())) {
	    			//业务库中的第三方接口处理入口 TODO
	    			
	    		 }else {
	    			 page=doBusinessByGet(request,apiManage,response);
	    			 
	    		 }
	    	 }
		}else {
			throw new DoAuthenticationFailException("认证失败!请检查参数名称或者appKey是否正确!");
		}
		return page;
	}
	private String getOssFilePath(String fileApiPath, String expires, String oSSAccessKeyId, String signature,
			Map<String, Object> pMap) {
		StringBuffer sb=new StringBuffer();
		StrSubstitutor ssub=new StrSubstitutor(pMap);
		String tempPath = ssub.replace(fileApiPath);
		return sb.append(tempPath).append("?").append(expires).append("&").append(oSSAccessKeyId).append("&").append(signature).toString();
	}
	/**
	 * 
	 * @Description: OSS上把对象的权限设置为可读写的权限 
	 * @date:   2019年7月30日 下午4:37:17  
	 * @author: wangshunyi    
	 * @throws
	 */
	private String getSimpleOssFilePath(String fileApiPath,Map<String, Object> pMap) {
		StringBuffer sb=new StringBuffer();
		StrSubstitutor ssub=new StrSubstitutor(pMap);
		String tempPath = ssub.replace(fileApiPath);
		return tempPath;
	}

	/**
	 * @throws ApiVersionIsDeleteException 
	 * @throws ApiVersionIsNotVerifyPassException 
	 * @throws ApiVersionIsDisableException 
	 * @throws ApiIsDeleteException 
	 * @throws ApiIsDisableException 
	 * @throws RequestURIErrorException 
	 * 
	 * @Description:根据请求的url去缓存中查询接口的信息
	 * @date:   2019年4月29日 下午2:40:16  
	 * @author: wangshunyi    
	 * @throws
	 */
	@Override
	public ApiManage getApiManage(String requestURI,String method) throws RequestURIErrorException, ApiIsDisableException, ApiIsDeleteException, ApiVersionIsDisableException, ApiVersionIsNotVerifyPassException, ApiVersionIsDeleteException {
		String cacheKey=(method.toLowerCase()+requestURI).replace("/", ":");
		ApiManage apiManage =null;// (ApiManage) CacheGet.getObject(cacheKey);
		//双重检测锁机制 在高并发场景下防止缓存穿透的问题
		if(null==apiManage) {
			synchronized(this) {
				//从redis中取一遍数据
			//	apiManage = (ApiManage) CacheGet.getObject(cacheKey);
				if(null==apiManage) {
					//缓存为null,从数据库中查询数据
					//apiManage=apiManageService.selectApiManageAndApiversionIdByApiIdAndVersionStatusAndVerifyStatusAndDeleteStatus(requestURI);
					//if(null==apiManage) {
					//throw new RequestURIErrorException("请求url错误或者接口被禁用或者接口版本被禁用或者接口审核未通过,请检查!");
					ApiManage manage = apiManageService.selectApiManageByUrl(requestURI);
					if(null==manage) {
						throw new RequestURIErrorException("请求url错误!");
					}else if(manage.getApiStatus().equals(ApiStatusEnum.DISABLE.getStatus())) {
						throw new ApiIsDisableException("请求的接口处于禁用状态!");
						
					}else if(manage.getDeleteStatus().equals(DeleteStatusEnum.DELETE.getStatus())) {
						throw new ApiIsDeleteException("请求的接口处于删除状态!");
						
					}else {
						ApiManage apiManageAndApiversion=apiManageService.selectApiManageAndApiversionByUrlAndEnable(requestURI); 
						if(null==apiManageAndApiversion) {
							throw new ApiVersionIsDisableException("请求接口版本的状态是禁用状态!");
						}else if(!(apiManageAndApiversion.getApiVerifyStatus().equals(ApiVerifyStatusEnum.VERIFY_PASS.getStatus()))) {
							throw new ApiVersionIsNotVerifyPassException("请求接口版本未通过审核!");
						}else if(apiManageAndApiversion.getApiDeleteStatus().equals(DeleteStatusEnum.DELETE.getStatus())) {
							throw new ApiVersionIsDeleteException("请求接口版本已经删除!");
						}else {
							apiManage=apiManageAndApiversion;
						}
					}
					//把数据库中查询出来的数据放入缓存中 过期时间设置为8个小时
					CachePut.putObject(cacheKey, apiManage, 8*60*60);
			}
			
		}
	}
	return apiManage;
 }

	@Override
	public Object doGetServiceByAppKeyRedis(ApiManage apiManage,DatabaseSource databaseSource,JSONObject jsonParam) throws AppKeyIsNotNullException, ApplyIsNotOnException, AppKeyIsNotExistException, ApplyIsNotCurrentApplyException {

		Object retObj= getRedisResult(apiManage,databaseSource,jsonParam);
		//根据命令类型查询redis
		return retObj;
	}

	public BaseResponse doPutService(HttpServletRequest request,HttpServletResponse response) throws DatabaseSourceIsNullException, AppKeyIsNotNullException, DoAuthenticationFailException, RequestParamIsNotMatchException, ApplyIsNotOnException, RequestURIErrorException, ApiIsDisableException, ApiIsDeleteException, ApiVersionIsDisableException, ApiVersionIsNotVerifyPassException, ApiVersionIsDeleteException {
		BaseResponse responseResult=null;
		String appKey=request.getHeader("appKey");
		if(StringUtils.isEmpty(appKey)){
			appKey= request.getParameter("appKey");
		}
		if(StringUtils.isBlank(appKey)) {
			throw new AppKeyIsNotNullException("接口应用的appKey不能为空!");
		}
		if(log.isInfoEnabled()) {
			log.info("appKey="+appKey);
		}
		if(!doCheckingApplyIsOn(appKey)) {
			throw new ApplyIsNotOnException("当前appKey对应的应用还未上线!");
		}
		//ApiManage apiManage = apiManageService.selectApiManageAndApiversionIdByApiIdAndVersionStatusAndVerifyStatusAndDeleteStatus(request.getRequestURI());
		ApiManage apiManage = getApiManage(request.getRequestURI().replace("/weather-api", ""),request.getMethod());
		if(doAuthentication(request,response,appKey)) {
			//做认证成功以后的操作
			Map<String, Object> resMap=null;
		    //业务库中的插入操作
			//String requestBodyJsonStr = getRequestBodyStr(request);
			//业务库中的插入操作   以流的方式传递 在验证的时候读取过一次，现在继续读取就没有数据了
			//String requestBodyJsonStr = getRequestBodyStr(request);
			String requestBodyJsonStr=(String) request.getAttribute("requestBodyJsonStr");
			//将requestBody中请求字符串转化为map
			 resMap = SignUtil.convertJsonToMap(requestBodyJsonStr);
			// 去掉签名信息
			 resMap.remove("sign");
			 List<UpdateField> updateFieldList = updateFieldService.selectUpdateFieldListByApiVersionId(apiManage.getApiVersionId());
			 Set<String> updateFieldPenNameSet=new HashSet<String>();
			 for (UpdateField updateField : updateFieldList) {
				 //在实际环境中测试一段时间考虑用不用只取必须字段
				 updateFieldPenNameSet.add(updateField.getPenName());
			}
			 //更新操作更新字段和where条件的key合并之后作比较
			 Set<String> requestParamPenNameSet=new HashSet<String>();
			 List<ApiRequestParam> apiRequestParamList= apiRequestParamService.selectApiRequestParamListByApiVersionId(apiManage.getApiVersionId());
			 for (ApiRequestParam apiRequestParam : apiRequestParamList) {
				 requestParamPenNameSet.add(apiRequestParam.getPenName());
				
			}
			 updateFieldPenNameSet.addAll(requestParamPenNameSet);
			 if(isSetEqual(updateFieldPenNameSet, resMap.keySet())) {
				 DatabaseSource databaseSource = databaseSourceService.getDatabaseSourceDetails(apiManage.getDatabaseSourceId());
				 if(databaseSource==null) {
					 throw new DatabaseSourceIsNullException("接口的数据源为空，请检查配置!");
				 }
				 log.info("数据库中存储的sql:"+apiManage.getSqlTemplet());
				 NamedParameterJdbcTemplate namedParameterJdbcTemplate = NamedParameterJdbcTemplateUtil.getNamedParameterJdbcTemplate(databaseSource.getDatabaseIP(), databaseSource.getPort(), databaseSource.getDatabaseName(), databaseSource.getUserName(), databaseSource.getPassword());
				 int update = namedParameterJdbcTemplate.update(apiManage.getSqlTemplet().replaceAll(REGEXP, ""), resMap);
				 if(update!=0) {
					 log.info("更新成功,一共更新了"+update+"条记录");
					 responseResult=new BaseResponse("200","更新成功,一共更新了"+update+"条记录",null);
				 }else {
					 responseResult=new BaseResponse("700","更新失败,请求条件为:【"+SignUtil.convertMapToJson(resMap)+"】没有匹配的记录,请检查查询条件!",null);
				 }
			 }else {
				 log.info("请求参数不匹配,请更正以后再访问!");
				 throw new RequestParamIsNotMatchException("请求参数不匹配,请更正以后再访问!");
			 }
		}else {
			throw new DoAuthenticationFailException("认证失败!请检查参数名称或者appKey是否正确!");
			
		}
		return responseResult;
	}
	public BaseResponse doDeleteService(HttpServletRequest request,HttpServletResponse response) throws AppKeyIsNotNullException,DatabaseSourceIsNullException, RequestParamIsNotMatchException, DoAuthenticationFailException, ApplyIsNotOnException, RequestURIErrorException, ApiIsDisableException, ApiIsDeleteException, ApiVersionIsDisableException, ApiVersionIsNotVerifyPassException, ApiVersionIsDeleteException {
		BaseResponse responseResult=null;
		String appKey=request.getHeader("appKey");
		if(StringUtils.isEmpty(appKey)){
			appKey= request.getParameter("appKey");
		}
		if(StringUtils.isBlank(appKey)) {
			throw new AppKeyIsNotNullException("接口应用的appKey不能为空!");
		}
		if(log.isInfoEnabled()) {
			log.info("appKey="+appKey);
		}
		if(!doCheckingApplyIsOn(appKey)) {
			throw new ApplyIsNotOnException("当前appKey对应的应用还未上线!");
		}
		//ApiManage apiManage = apiManageService.selectApiManageAndApiversionIdByApiIdAndVersionStatusAndVerifyStatusAndDeleteStatus(request.getRequestURI());
		ApiManage apiManage = getApiManage(request.getRequestURI().replace("/weather-api", ""),request.getMethod());
		if(doAuthentication(request,response,appKey)) {
			//做认证成功以后的操作
			Map<String, Object> resMap=null;
		    //业务库中的插入操作
			//String requestBodyJsonStr = getRequestBodyStr(request);
			//业务库中的插入操作   以流的方式传递 在验证的时候读取过一次，现在继续读取就没有数据了
			//String requestBodyJsonStr = getRequestBodyStr(request);
			String requestBodyJsonStr=(String) request.getAttribute("requestBodyJsonStr");
			//将requestBody中请求字符串转化为map
			 resMap = SignUtil.convertJsonToMap(requestBodyJsonStr);
			// 去掉签名信息
			 resMap.remove("sign");
			 Set<String> requestParamPenNameSet=new HashSet<String>();
			 List<ApiRequestParam> apiRequestParamList= apiRequestParamService.selectApiRequestParamListByApiVersionId(apiManage.getApiVersionId());
			 for (ApiRequestParam apiRequestParam : apiRequestParamList) {
				 requestParamPenNameSet.add(apiRequestParam.getPenName());
			}
			 if(isSetEqual(requestParamPenNameSet, resMap.keySet())) {
				 DatabaseSource databaseSource = databaseSourceService.getDatabaseSourceDetails(apiManage.getDatabaseSourceId());
				 if(databaseSource==null) {
					 throw new DatabaseSourceIsNullException("接口的数据源为空，请检查配置!");
				 }
				 log.info("数据库中存储的sql:"+apiManage.getSqlTemplet());
				 NamedParameterJdbcTemplate namedParameterJdbcTemplate = NamedParameterJdbcTemplateUtil.getNamedParameterJdbcTemplate(databaseSource.getDatabaseIP(), databaseSource.getPort(), databaseSource.getDatabaseName(), databaseSource.getUserName(), databaseSource.getPassword());
				 int update = namedParameterJdbcTemplate.update(apiManage.getSqlTemplet().replaceAll(REGEXP, ""), resMap);
				 if(update!=0) {
					 log.info("删除成功,一共删除了"+update+"条记录");
					 responseResult=new BaseResponse("200","删除成功,一共删除了"+update+"条记录",null);
				 }else {
					 responseResult=new BaseResponse("700","删除失败,请求条件为:【"+SignUtil.convertMapToJson(resMap)+"】没有匹配的记录,请检查查询条件!",null);
				 }
			 }else {
				 log.info("请求参数不匹配,请更正以后再访问!");
				 throw new RequestParamIsNotMatchException("请求参数不匹配,请更正以后再访问!");
			 }
		}else {
			log.info("认证失败!");
			throw new DoAuthenticationFailException("认证失败!请检查参数名称或者appKey是否正确!");
			
		}
		return responseResult;
	}
	/**
	 * @throws AppKeyIsNotNullException 
	 * 
	 * @Description: 统一做接口服务认证操作   
	 * @date:   2019年4月28日 上午10:33:35  
	 * @author: wangshunyi    
	 * @throws
	 */
	private boolean doAuthentication(HttpServletRequest request, HttpServletResponse response, String appKey) {
		if (request.getMethod().equals(REQUEST_METHOD_GET)) {
			Map<String, Object> resMap = null;
			Map<String, String[]> parameterMap = request.getParameterMap();
			Map<String, Object> pMap = new HashMap<String, Object>();
			Set<String> keys = parameterMap.keySet();
			for (String key : keys) {
				pMap.put(key, parameterMap.get(key)[0]);
			}
			//String convertMapToJson = SignUtil.convertMapToJson(pMap);
			//resMap = SignUtil.convertJsonToMap(convertMapToJson);
			resMap=pMap;
			// 取出请求参数中的sign
			String signature = (String) resMap.get("sign");
			// 去掉签名信息
			resMap.remove("sign");
			// 服务器端拿到请求头中的appKey和请求参数按照客户端的规则生成新的签名 新的签名和客户端生成的签名匹配则认证成功
			if (SignUtil.signVerify(appKey, resMap, signature)) {
				if (log.isInfoEnabled()) {
					log.info("验签成功：" + signature);
				}
				return true;
			} else {
				return false;
			}
		} else {
			Map<String, Object> resMap = null;
			String requestBodyJsonStr = "";
			try {
				requestBodyJsonStr = getRequestBodyStr(request);
				request.setAttribute("requestBodyJsonStr", requestBodyJsonStr);
			} catch (IOException e) {
				e.printStackTrace();
			}
			// 将requestBody中请求字符串转化为map
			resMap = SignUtil.convertJsonToMap(requestBodyJsonStr);
			// 取出请求参数中的sign
			String signature = (String) resMap.get("sign");
			// 去掉签名信息
			resMap.remove("sign");
			// 服务器端拿到请求的appKey和请求参数按照客户端的规则生成新的签名 新的签名和客户端生成的签名匹配则认证成功
			if (SignUtil.signVerify(appKey, resMap, signature)) {
				if (log.isInfoEnabled()) {
					log.info("验签成功：" + signature);
				}
				return true;
			} else {
				return false;
			}
		}
	}
	//文件接口的认证
	private boolean doFileAuthentication(HttpServletRequest request, HttpServletResponse response, String appKey) {
			Map<String, Object> resMap = null;
			Map<String, String[]> parameterMap = request.getParameterMap();
			Map<String, Object> pMap = new HashMap<String, Object>();
			Set<String> keys = parameterMap.keySet();
			for (String key : keys) {
				pMap.put(key, parameterMap.get(key)[0]);
			}
			//String convertMapToJson = SignUtil.convertMapToJson(pMap);
			//resMap = SignUtil.convertJsonToMap(convertMapToJson);
			resMap=pMap;
			// 取出请求参数中的sign
			String signature = (String) resMap.get("sign");
			// 去掉签名信息
			resMap.remove("sign");
			// 服务器端拿到请求头中的appKey和请求参数按照客户端的规则生成新的签名 新的签名和客户端生成的签名匹配则认证成功
			if (SignUtil.signVerify(appKey, resMap, signature)) {
				if (log.isInfoEnabled()) {
					log.info("验签成功：" + signature);
				}
				return true;
			} else {
				return false;
			}
	}
	/**
	 * 
	 * @Description:获取 request body中的请求字符  (POST的方式是以流的方式传输的,只能读取一次)
	 * @param: request请求对象     
	 * @return:  
	 * @date:   2019年3月30日 上午10:41:52  
	 * @author: wangshunyi    
	 * @throws
	 */
	public  String getRequestBodyStr(ServletRequest request) throws IOException {
		BufferedReader reader = request.getReader();
		String str;
		String wholeStr="";
		while((str=reader.readLine())!=null) {
			wholeStr+=str;
		}
		return wholeStr;
	}
	private  boolean isSetEqual(Set set1, Set set2) {  
		  if (set1 == null && set2 == null) {  
		   return true;
		  }  
		  if(set1.size()==0&&set2.size()==0) {
			  return true;
		  }
		/*  if (set1 == null || set2 == null || set1.size() != set2.size()
		    || set1.size() == 0 || set2.size() == 0) {  
			 return false;
		  } */
		  Iterator ite1 = set1.iterator();  
		  Iterator ite2 = set2.iterator();  
		  boolean isFullEqual = true;  
		 while (ite2.hasNext()) {  
		   if (!set1.contains(ite2.next())) {  
		    isFullEqual = false;  
		   }  
		  }
		  return isFullEqual;  
		 }  
	
	private String doSubjectOutSideByGet(HttpServletRequest request, ApiManage apiManage,HttpServletResponse response) {
		   //处理主题库中的第三方GET请求
		 Map<String, Object> pMap = getRequestParamMapByGet(request);
		 log.info(">>>从get请求中获取参数数据="+JSONObject.toJSONString(pMap));
		 pMap.remove("appKey");
		 log.info(">>>从get请求中删除appKey获取参数数据="+JSONObject.toJSONString(pMap));
				String outSideUrlParams = getUrlStrParamsByMap(apiManage.getOutsideUrl(),pMap);
		 log.info(">>>第三方请求接口url="+outSideUrlParams);
		 log.info(">>>接口在本系统结束执行时间="+DateUtils.getDate(new Date()));
				String resultStr = doOutSideGetApi(outSideUrlParams, pMap, apiManage.getDataFormat());
		return resultStr;
	}
	/**
	 * 
	 * @Description: 获取发送GET请求的参数并返回一个Map
	 * @date:   2019年4月11日 上午10:10:51  
	 * @author: wangshunyi    
	 * @throws
	 */
	private Map<String,Object> getRequestParamMapByGet(ServletRequest request) {
		Map<String, String[]> parameterMap = request.getParameterMap();
		Map<String, Object> pMap =new HashMap<String,Object>();
		Set<String> keys= parameterMap.keySet();
		for (String key : keys) {
			pMap.put(key, parameterMap.get(key)[0]);
			
		}
		return pMap;
	}
	/**
	 * 
	 * @Description: 第三方地址的url 格式 http://localhost:8080/v1/apiManage/apiVersionDetails
	 * @param:map 拼接参数的占位符      
	 * @date:   2019年4月4日 下午3:24:31  
	 * @author: wangshunyi    
	 * @throws
	 */
	private String getUrlParamsByMap(String url,Map<String, Object> map) {
        if (map == null) {
            return "";
        }
        StringBuffer sb = new StringBuffer();
        sb.append(url).append("?");
        for (Map.Entry<String, Object> entry : map.entrySet()) {
            sb.append(entry.getKey() + "={" + entry.getKey()+"}");
            sb.append("&");
        }
        String s = sb.toString();
        if (s.endsWith("&")) {
            s = s.substring(0, s.length() - 1);
        }
        return s;
    }
	/**
	 * 
	 * @Description: 第三方地址的url 格式 http://localhost:8080/v1/apiManage/apiVersionDetails
	 * @param:map 拼接参数的占位符      
	 * @date:   2019年4月4日 下午3:24:31  
	 * @author: wangshunyi    
	 * @throws
	 */

	private static  String getUrlStrParamsByMap(String url,Map<String, Object> map) {
        if (map.isEmpty()) {
            return  url;
        }
        StringBuffer sb = new StringBuffer();
        if(url.indexOf('?')==-1) {
        	sb.append(url).append("?");
        }else {
        	 sb.append(url).append("&");
        }
        for (Map.Entry<String, Object> entry : map.entrySet()) {
        	sb.append(entry.getKey() + "=" + entry.getValue());
            sb.append("&");
        }
        String s = sb.toString();
        if (s.endsWith("&")) {
            s = s.substring(0, s.length() - 1);
        }
        return s;
    }
	

	/**
	 * 
	 * @Description:Get请求下转发第三方请求
	 * @param: url 第三方请求的url  
	 * @param: paramMap 请求参数的url 
	 * @param: contentType  
	 * @return:   返回一个字符串
	 * @date:   2019年4月4日 下午3:10:47  
	 * @author: wangshunyi    
	 * @throws
	 */
	@SuppressWarnings("unlikely-arg-type")
	private String doOutSideGetApi(String url,Map<String,Object> paramMap,String dataFormat) {
		// 添加请求头信息
		log.info(">>>>开始执行第三方接口,接口地址为="+url);
		long startTime=System.currentTimeMillis();
		HttpHeaders headers = new HttpHeaders(); 
		if(dataFormat.equals(MediaType.APPLICATION_JSON_UTF8)) {
			  headers.setContentType(MediaType.APPLICATION_JSON_UTF8);
		}
	   
		if(dataFormat.equals(MediaType.APPLICATION_FORM_URLENCODED)) {
			headers.setContentType(MediaType.APPLICATION_FORM_URLENCODED);
		}
		
		if(dataFormat.equals(MediaType.APPLICATION_XML)) {
			headers.setContentType(MediaType.APPLICATION_XML);
		}
		//headers.set("token", token);
		//headers.setContentType(mediaType);
		HttpEntity<Object> requestHeaders = new HttpEntity<Object>(null, headers);
		if(log.isInfoEnabled()) {
			log.info("this OutSideGetApi Request Headers===========:"+JSON.toJSONString(headers));
		}
		RestTemplate restTemplate = new RestTemplate();
		ResponseEntity<String> exchange = restTemplate.exchange(url,HttpMethod.GET,requestHeaders, String.class, paramMap);
		String body = exchange.getBody();
		//log.info(">>>>第三方接口执行成功,响应值="+JSONObject.toJSONString(body));
		long endTime=System.currentTimeMillis();
		log.info(">>>接口从发送请求到【外部系统】执行完返回一共耗时间="+String.valueOf(endTime-startTime));
		return body;
	}
	private PageInfo doSubjectByGet(HttpServletRequest request, ApiManage apiManage,HttpServletResponse response) throws DoAuthenticationFailException, RequestParamIsNotMatchException, DatabaseSourceIsNullException {
    	//处理主题库中的Get请求
    	Map<String, Object> resMap=null;
		Map<String, String[]> parameterMap = request.getParameterMap();
		Map<String, Object> pMap =new HashMap<String,Object>();
		Set<String> keys= parameterMap.keySet();
		for (String key : keys) {
			pMap.put(key, parameterMap.get(key)[0]);
		}
		// 去掉签名信息
		pMap.remove("sign");
		//服务器端拿到请求的token和请求参数按照客户端的规则生成新的签名  新的签名和客户端生成的签名匹配就可以访问数据
		List<ApiRequestParam> apiRequestParamList= apiRequestParamService.selectApiRequestParamListByApiVersionId(apiManage.getApiVersionId());
		Set<String> penNameSet=new HashSet<String>();
		for (ApiRequestParam apiRequestParam : apiRequestParamList) {
			//把必须的请求参数取出来
			//if(apiRequestParam.getIsRequired().equals(YesOrNoStatusEnum.YES.getLabel())) {
				//把请求参数笔名取出来
				penNameSet.add(apiRequestParam.getPenName());
			//}
		}
		Set<String> requestSet=pMap.keySet();
		if(isSetEqual(penNameSet,requestSet)) {
			//String convertMapToJsonStr = SignUtil.convertMapToJson(resMap);
			//JSONArray jsonStrToJSONArray = jsonArrayStrToJSONArray(convertMapToJsonStr);
			DatabaseSource databaseSource = databaseSourceService.getDatabaseSourceDetails(apiManage.getDatabaseSourceId());
			if(databaseSource!=null) {
				NamedParameterJdbcTemplate namedParameterJdbcTemplate = NamedParameterJdbcTemplateUtil.getNamedParameterJdbcTemplate(databaseSource.getDatabaseIP(), databaseSource.getPort(), databaseSource.getDatabaseName(), databaseSource.getUserName(), databaseSource.getPassword());
				 log.info("数据库中存储的sql:"+apiManage.getSqlTemplet());
				Page page=new Page(apiManage.getSqlTemplet().replaceAll(REGEXP, ""),1,10, namedParameterJdbcTemplate,pMap);
				//List<Map<String, Object>> resultMap = doJdbcConnectionAndGetResult(databaseSource.getDatabaseIP(),"3306",databaseSource.getDatabaseName(),databaseSource.getUserName(),databaseSource.getPassword(),jsonStrToJSONArray,apiManage.getSqlTemplet());
		    	//返回给调用方
				PageInfo pageInfo=new PageInfo();
				pageInfo.setPageSize(page.getPageSize());
				pageInfo.setPageNum(page.getCurrentPage());
				pageInfo.setSize(page.getTotalRows());
				pageInfo.setPages(page.getTotalPages());
				pageInfo.setStartRow(page.getStartIndex());
				pageInfo.setEndRow(page.getLastIndex());
				pageInfo.setList(page.getresult());
		    	//BaseResponse resultResponse=new BaseResponse(200,"查询成功",page);
		    	return pageInfo;
				}else {
					log.info("数据源为空!");
					throw new DatabaseSourceIsNullException("接口的数据源为空，请检查配置!");
				}
		}else {
			log.info("请求参数名称不匹配");
			throw new RequestParamIsNotMatchException("请求参数名称不匹配,请检查!");
	  }
	}
	private PageInfo doSubjectByGetByAppKey(HttpServletRequest request, ApiManage apiManage,HttpServletResponse response) throws Exception {
		//处理主题库中的Get请求
		Map<String, Object> resMap=null;
		Map<String, String[]> parameterMap = request.getParameterMap();
		Map<String, Object> pMap =new HashMap<String,Object>();
		Set<String> keys= parameterMap.keySet();
		for (String key : keys) {
			pMap.put(key, parameterMap.get(key)[0]);
		}
		// 去掉签名信息
		//pMap.remove("sign");
		//服务器端拿到请求的token和请求参数按照客户端的规则生成新的签名  新的签名和客户端生成的签名匹配就可以访问数据
		String queryField = request.getParameter("queryField");
		int pageNo =StringUtils.isBlank(request.getParameter("pageNo"))?this.pageNo:Integer.parseInt(request.getParameter("pageNo"));
		int pageSize =StringUtils.isBlank(request.getParameter("pageSize"))?this.pageSize:Integer.parseInt(request.getParameter("pageSize"));
		if(!doCheckPageNoAndPageSize(pageNo,pageSize)){
			throw new PageNoOrPageSizeNotRightException("你输入的分页参数不合法,[pageNo]的最不能小于"+this.pageNo+"==[pageSize]的值不能大于"+this.pageSize);
		}
		List<ApiRequestParam> apiRequestParamList= apiRequestParamService.selectApiRequestParamListByApiVersionId(apiManage.getApiVersionId());
		Set<String> penNameSet=new HashSet<String>();
		for (ApiRequestParam apiRequestParam : apiRequestParamList) {
			//把必须的请求参数取出来
			//if(apiRequestParam.getIsRequired().equals(YesOrNoStatusEnum.YES.getLabel())) {
			//把请求参数笔名取出来
			penNameSet.add(apiRequestParam.getPenName());
			//}
		}
		Set<String> requestSet=pMap.keySet();
		requestSet.remove("appKey");
		requestSet.remove("pageNo");
		requestSet.remove("pageSize");
		requestSet.remove("queryField");
		if(isSetEqual(penNameSet,requestSet)) {
			//String convertMapToJsonStr = SignUtil.convertMapToJson(resMap);
			//JSONArray jsonStrToJSONArray = jsonArrayStrToJSONArray(convertMapToJsonStr);
			DatabaseSource databaseSource = databaseSourceService.getDatabaseSourceDetails(apiManage.getDatabaseSourceId());
			if(databaseSource!=null) {
				NamedParameterJdbcTemplate namedParameterJdbcTemplate = NamedParameterJdbcTemplateUtil.getNamedParameterJdbcTemplate(databaseSource.getDatabaseIP(), databaseSource.getPort(), databaseSource.getDatabaseName(), databaseSource.getUserName(), databaseSource.getPassword());
				String sqlTemplet = apiManage.getSqlTemplet();
				sqlTemplet=SqlTemplateUtils.getSqlTemplate(sqlTemplet,pMap);
				log.debug("数据库中存储的sql:"+sqlTemplet);
				if(sqlTemplet.contains("$")) {
					log.debug(">>>>>表作为参数传递数据库中的sql=:"+sqlTemplet);
					sqlTemplet = getReplaTagSqlTemplet(sqlTemplet,pMap);
					log.debug(">>>>>表作为参数传递替换以后的sql=:"+sqlTemplet);
				}
				log.debug("pageNo====:"+pageNo);
				log.debug("pageSize==:"+pageSize);
				if(StringUtils.isNotEmpty(queryField)){
					sqlTemplet = "select "+queryField +" from ( "+sqlTemplet+" ) tb ";
				}
				//Page page=new Page(apiManage.getSqlTemplet().replaceAll(REGEXP, ""),1,10, namedParameterJdbcTemplate,pMap);
				//Page page=new Page(apiManage.getSqlTemplet().replaceAll(REGEXP, ""),1,10, namedParameterJdbcTemplate,pMap);
				Page page=new Page(sqlTemplet,pageNo,pageSize, namedParameterJdbcTemplate,pMap);
				//List<Map<String, Object>> resultMap = doJdbcConnectionAndGetResult(databaseSource.getDatabaseIP(),"3306",databaseSource.getDatabaseName(),databaseSource.getUserName(),databaseSource.getPassword(),jsonStrToJSONArray,apiManage.getSqlTemplet());
				//返回给调用方
				PageInfo pageInfo=new PageInfo();
				pageInfo.setPageSize(page.getPageSize());
				pageInfo.setPageNum(page.getCurrentPage());
				pageInfo.setSize(page.getTotalRows());
				pageInfo.setPages(page.getTotalPages());
				pageInfo.setTotal(page.getTotalRows());
				pageInfo.setStartRow(page.getStartIndex());
				pageInfo.setEndRow(page.getLastIndex());
				pageInfo.setList(page.getresult());
				//BaseResponse resultResponse=new BaseResponse(200,"查询成功",page);
				return pageInfo;
			}else {
				log.error("数据源为空!");
				throw new DatabaseSourceIsNullException("接口的数据源为空，请检查配置!");
			}
		}else {
			log.error("请求参数名称不匹配");
			throw new RequestParamIsNotMatchException("请求参数名称不匹配,请检查!");
		}
	}
	private PageInfo doBusinessByGet(HttpServletRequest request, ApiManage apiManage,
			HttpServletResponse response) throws Exception {
    	    Map<String, Object> resMap=null;
    		Map<String, String[]> parameterMap = request.getParameterMap();
    		Map<String, Object> pMap =new HashMap<String,Object>();
    		Set<String> keys= parameterMap.keySet();
    		for (String key : keys) {
    			pMap.put(key, parameterMap.get(key)[0]);
			}
    		resMap=pMap;
			// 去掉签名信息
			resMap.remove("sign");
		    //本地的接口
			List<ApiRequestParam> apiRequestParamList= apiRequestParamService.selectApiRequestParamListByApiVersionId(apiManage.getApiVersionId());
			Set<String> penNameSet=new HashSet<String>();
			for (ApiRequestParam apiRequestParam : apiRequestParamList) {
					penNameSet.add(apiRequestParam.getPenName());
			}
		   int pageNo =StringUtils.isBlank(request.getParameter("pageNo"))?this.pageNo:Integer.parseInt(request.getParameter("pageNo"));
		   int pageSize =StringUtils.isBlank(request.getParameter("pageSize"))?this.pageSize:Integer.parseInt(request.getParameter("pageSize"));
		   String queryField = request.getParameter("queryField");
			Set<String> requestKeys=resMap.keySet();
	    	requestKeys.remove("pageNo");
		    requestKeys.remove("pageSize");
		    requestKeys.remove("queryField");
			if(isSetEqual(penNameSet,requestKeys)) {
				DatabaseSource databaseSource = databaseSourceService.getDatabaseSourceDetails(apiManage.getDatabaseSourceId());
				String sqlTemplet = apiManage.getSqlTemplet();
				sqlTemplet=SqlTemplateUtils.getSqlTemplate(sqlTemplet,pMap);
				if(databaseSource!=null) {
					log.info("数据库中存储的sql:"+apiManage.getSqlTemplet());
					NamedParameterJdbcTemplate namedParameterJdbcTemplate = NamedParameterJdbcTemplateUtil.getNamedParameterJdbcTemplate(databaseSource.getDatabaseIP(), databaseSource.getPort(), databaseSource.getDatabaseName(), databaseSource.getUserName(), databaseSource.getPassword());
					//Page page=new Page(apiManage.getSqlTemplet().replaceAll(REGEXP, ""), Integer.parseInt(String.valueOf(resMap.get("pageNo"))), Integer.parseInt(String.valueOf(resMap.get("pageSize"))), namedParameterJdbcTemplate,resMap);
					sqlTemplet=getReplaTagSqlTemplet(sqlTemplet,pMap);
					if(StringUtils.isNotEmpty(queryField)){
						sqlTemplet = "select "+queryField +" from ( "+sqlTemplet+" ) tb ";
					}
					Page page=new Page(sqlTemplet.replaceAll(REGEXP, ""),pageNo,pageSize,namedParameterJdbcTemplate,resMap);
					//List<Map<String, Object>> resultMap = doJdbcConnectionAndGetResult(databaseSource.getDatabaseIP(),"3306",databaseSource.getDatabaseName(),databaseSource.getUserName(),databaseSource.getPassword(),jsonStrToJSONArray,apiManage.getSqlTemplet());
			    	//返回给调用方
			    	//BaseResponse resultResponse=new BaseResponse(200,"查询成功",page);
			    	 //return  resultResponse;
					PageInfo pageInfo=new PageInfo();
					pageInfo.setPageSize(page.getPageSize());
					pageInfo.setPageNum(page.getCurrentPage());
					pageInfo.setSize(page.getTotalRows());
					pageInfo.setPages(page.getTotalPages());
					pageInfo.setStartRow(page.getStartIndex());
					pageInfo.setEndRow(page.getLastIndex());
					pageInfo.setList(page.getresult());
					return pageInfo;
					}else {
						log.info("接口的数据源为空，请检查配置!");
					 throw new DoAuthenticationFailException("接口的数据源为空，请检查配置!");
						
					}
			   }else {
				 log.info("请求参数名称不匹配,请检查!");
				  throw new RequestParamIsNotMatchException("请求参数名称不匹配,请检查!");
			}
	}
	private PageInfo doBusinessByGetByAppKey(HttpServletRequest request, ApiManage apiManage,
			HttpServletResponse response) throws Exception {
		Map<String, Object> resMap=null;
		Map<String, String[]> parameterMap = request.getParameterMap();
		Map<String, Object> pMap =new HashMap<String,Object>();
		Set<String> keys= parameterMap.keySet();
		for (String key : keys) {
			pMap.put(key, parameterMap.get(key)[0]);
		}
		resMap=pMap;
		// 去掉签名信息
		//resMap.remove("sign");
		//本地的接口
		String queryField = request.getParameter("queryField");
		log.debug("=====pageNo===="+request.getParameter("pageNo"));
		log.debug("=====pageSize===="+request.getParameter("pageSize"));
		log.debug("=====queryField===="+queryField);

		int pageNo =StringUtils.isBlank(request.getParameter("pageNo"))?this.pageNo:Integer.parseInt(request.getParameter("pageNo"));
		int pageSize =StringUtils.isBlank(request.getParameter("pageSize"))?this.pageSize:Integer.parseInt(request.getParameter("pageSize"));
		if(!doCheckPageNoAndPageSize(pageNo,pageSize)){
			throw new PageNoOrPageSizeNotRightException("你输入的分页参数不合法,[pageNo]的最不能小于"+this.pageNo+"==[pageSize]的值不能大于"+this.pageSize);
		}

		List<ApiRequestParam> apiRequestParamList= apiRequestParamService.selectApiRequestParamListByApiVersionId(apiManage.getApiVersionId());
		Set<String> penNameSet=new HashSet<String>();
		for (ApiRequestParam apiRequestParam : apiRequestParamList) {
			penNameSet.add(apiRequestParam.getPenName());
		}

		Set<String> requestKeys=resMap.keySet();
		requestKeys.remove("appKey");
		requestKeys.remove("pageNo");
		requestKeys.remove("pageSize");
		requestKeys.remove("queryField");
		if(isSetEqual(penNameSet,requestKeys)) {
			DatabaseSource databaseSource = databaseSourceService.getDatabaseSourceDetails(apiManage.getDatabaseSourceId());
			String sqlTemplet = apiManage.getSqlTemplet();
			sqlTemplet=SqlTemplateUtils.getSqlTemplate(sqlTemplet,pMap);
			if(databaseSource!=null) {
				if(sqlTemplet.contains("$")) {
					log.debug(">>>>>表作为参数传递数据库中的sql=:"+sqlTemplet);
					sqlTemplet=getReplaTagSqlTemplet(sqlTemplet,pMap);
					log.debug(">>>>>表作为参数传递替换以后的sql=:"+sqlTemplet);
				}
				log.debug("数据库中存储的sql:"+sqlTemplet);
				log.debug("pageNo====:"+pageNo);
				log.debug("pageSize==:"+pageSize);
				if(StringUtils.isNotEmpty(queryField)){
					sqlTemplet = "select "+queryField +" from ( "+sqlTemplet+" ) tb ";
				}
				NamedParameterJdbcTemplate namedParameterJdbcTemplate = NamedParameterJdbcTemplateUtil.getNamedParameterJdbcTemplate(databaseSource.getDatabaseIP(), databaseSource.getPort(), databaseSource.getDatabaseName(), databaseSource.getUserName(), databaseSource.getPassword());
				//Page page=new Page(apiManage.getSqlTemplet().replaceAll(REGEXP, ""), Integer.parseInt(String.valueOf(resMap.get("pageNo"))), Integer.parseInt(String.valueOf(resMap.get("pageSize"))), namedParameterJdbcTemplate,resMap);
				//Page page=new Page(apiManage.getSqlTemplet().replaceAll(REGEXP, ""),1,10,namedParameterJdbcTemplate,resMap);
				Page page=new Page(sqlTemplet,pageNo,pageSize,namedParameterJdbcTemplate,resMap);
				//List<Map<String, Object>> resultMap = doJdbcConnectionAndGetResult(databaseSource.getDatabaseIP(),"3306",databaseSource.getDatabaseName(),databaseSource.getUserName(),databaseSource.getPassword(),jsonStrToJSONArray,apiManage.getSqlTemplet());
				//返回给调用方
				//BaseResponse resultResponse=new BaseResponse(200,"查询成功",page);
				//return  resultResponse;
				PageInfo pageInfo=new PageInfo();
				pageInfo.setPageSize(page.getPageSize());
				pageInfo.setPageNum(page.getCurrentPage());
				pageInfo.setSize(page.getTotalRows());
				pageInfo.setPages(page.getTotalPages());
				pageInfo.setStartRow(page.getStartIndex());
				pageInfo.setEndRow(page.getLastIndex());
				pageInfo.setList(page.getresult());
				return pageInfo;
			}else {
				log.info("接口的数据源为空，请检查配置!");
				throw new DoAuthenticationFailException("接口的数据源为空，请检查配置!");
				
			}
		}else {
			log.info("请求参数名称不匹配,请检查!");
			throw new RequestParamIsNotMatchException("请求参数名称不匹配,请检查!");
		}
	}
	/**
	 * 
	 * @Description: 根据appKey检查应用是否上线   
	 * @date:   2019年5月21日 上午9:42:27  
	 * @author: wangshunyi    
	 * @throws
	 */
	private boolean doCheckingApplyIsOn(String appKey) {
		Apply app = applyManageService.selectApplyByAppKey(appKey);
		if(null==app) {
			return false;
		}
		return true;
	}
	
	private boolean doApplyByAppKeyIsExist(String applyKey) {
		Apply apply = applyManageService.selectApplyByAppKeyIsExist(applyKey);
		if(apply==null) {
			return false;
			
		}
		return true;
		
	}

	@Override
	public void doGetFileService(HttpServletRequest request, HttpServletResponse response) throws AppKeyIsNotNullException, ApplyIsNotOnException, FileApiExpiresOSSAccessKeyIdSignatureIsNullException, DoAuthenticationFailException, RequestURIErrorException, ApiIsDisableException, ApiIsDeleteException, ApiVersionIsDisableException, ApiVersionIsNotVerifyPassException, ApiVersionIsDeleteException, IOException {
		InputStream inputStream=null;
		String appKey=request.getHeader("appKey");
		if(StringUtils.isEmpty(appKey)){
			appKey= request.getParameter("appKey");
		}
		if(StringUtils.isBlank(appKey)) {
			throw new AppKeyIsNotNullException("接口应用的appKey不能为空!");
		}
		if(log.isInfoEnabled()) {
			log.info("appKey="+appKey);
		}
		if(!doCheckingApplyIsOn(appKey)) {
			throw new ApplyIsNotOnException("当前appKey对应的应用还未上线,请联系后台管理员...");
		}
		ApiManage apiManage = getApiManage(request.getRequestURI().replace("/weather-api", ""),request.getMethod());
		if(doFileAuthentication(request,response,appKey)) {
			//验证成功
			 if(apiManage.getApiType().equals(SUBJECT)) {
	    		 //主题库中的第三方接口
	    		 if(apiManage.getIsOutSide().equals(ApiRequestModeStatusEnum.YES.getStatus())) {
	    			 //doSubjectOutSideByGet(request,apiManage,response);
	    			 //文件接口
	    		 }else {
	    			 //主题库中的文件接口
	    			 //String expires = request.getHeader("Expires");
	    			 //String oSSAccessKeyId = request.getHeader("OSSAccessKeyId");
	    			// String signature = request.getHeader("Signature");
	    			// if(StringUtils.isEmpty(expires)||StringUtils.isEmpty(oSSAccessKeyId)||StringUtils.isEmpty(signature)) {
	    			//	 throw new FileApiExpiresOSSAccessKeyIdSignatureIsNullException("文件接口请求头中Expires或OSSAccessKeyId或Signature不能为空");
	    			// }
	    			 Map<String, String[]> parameterMap = request.getParameterMap();
	    				Map<String, Object> pMap =new HashMap<String,Object>();
	    				Set<String> keys= parameterMap.keySet();
	    				for (String key : keys) {
	    					pMap.put(key, parameterMap.get(key)[0]);
	    				}
	    			 log.info("数据库中存储的OSS路径:"+apiManage.getFileApiPath());
	    			 String ossFilePath = getSimpleOssFilePath(apiManage.getFileApiPath(),pMap);
	    			 log.info("OSS路径:"+ossFilePath);
	    			 inputStream=HttpClientUtils.sendFileHttpGet(null, ossFilePath, "UTF-8");
	    			 OutputStream outputStream = new BufferedOutputStream(response.getOutputStream());
	    				//创建存放文件内容的数组
	    				byte[] buff =new byte[1024];
	    				//所读取的内容使用n来接收
	    				int n;
	    				//当没有读取完时,继续读取,循环
	    				while((n=inputStream.read(buff))!=-1){
	    					//将字节数组的数据全部写入到输出缓冲流中
	    					outputStream.write(buff,0,n);
	    				}
	    				//强制将缓存区的数据进行输出
	    				outputStream.flush();
	    				//关流
	    				outputStream.close();
	    				inputStream.close();
	    		 }
	    		 //业务库
	    	 }else {
	    		
	    		 if(apiManage.getIsOutSide().equals(ApiRequestModeStatusEnum.YES.getStatus())) {
	    			//业务库中的第三方接口处理入口 TODO
	    			
	    		 }else{
	    			 //业务库中文件接口处理
	    			// String expires = request.getHeader("Expires");
	    			 //String oSSAccessKeyId = request.getHeader("OSSAccessKeyId");
	    			 //String signature = request.getHeader("Signature");
	    			 //if(StringUtils.isEmpty(expires)||StringUtils.isEmpty(oSSAccessKeyId)||StringUtils.isEmpty(signature)) {
	    			//	 throw new FileApiExpiresOSSAccessKeyIdSignatureIsNullException("文件接口请求头中Expires或OSSAccessKeyId或Signature不能为空");
	    			// }
	    			 Map<String, String[]> parameterMap = request.getParameterMap();
	    				Map<String, Object> pMap =new HashMap<String,Object>();
	    				Set<String> keys= parameterMap.keySet();
	    				for (String key : keys) {
	    					pMap.put(key, parameterMap.get(key)[0]);
	    				}
	    			 log.info("数据库中存储的OSS路径:"+apiManage.getFileApiPath());
	    			 String ossFilePath = getSimpleOssFilePath(apiManage.getFileApiPath(),pMap);
	    			 log.info("OSS路径:"+ossFilePath);
	    			 inputStream= HttpClientUtils.sendFileHttpGet(null, ossFilePath, "UTF-8");
	    			 OutputStream outputStream = new BufferedOutputStream(response.getOutputStream());
	    				//创建存放文件内容的数组
	    				byte[] buff =new byte[1024];
	    				//所读取的内容使用n来接收
	    				int n;
	    				//当没有读取完时,继续读取,循环
	    				while((n=inputStream.read(buff))!=-1){
	    					//将字节数组的数据全部写入到输出缓冲流中
	    					outputStream.write(buff,0,n);
	    				}
	    				//强制将缓存区的数据进行输出
	    				outputStream.flush();
	    				//关流
	    				outputStream.close();
	    				inputStream.close();
	    		 }
	    	 }
		}else {
			throw new DoAuthenticationFailException("认证失败!请检查参数名称或者appKey是否正确!");
		}
	}

	@Override
	public BaseResponse doPostServiceByAppKey(HttpServletRequest request, HttpServletResponse response) throws AppKeyIsNotNullException, AppKeyIsNotExistException, ApplyIsNotOnException, RequestURIErrorException, ApiIsDisableException, ApiIsDeleteException, ApiVersionIsDisableException, ApiVersionIsNotVerifyPassException, ApiVersionIsDeleteException, IOException, DatabaseSourceIsNullException, RequestParamIsNotMatchException, ApplyIsNotCurrentApplyException {
		BaseResponse responseResult=null;
		String appKey=request.getHeader("appKey");
		if(StringUtils.isEmpty(appKey)){
			appKey= request.getParameter("appKey");
		}
		if(StringUtils.isBlank(appKey)) {
			throw new AppKeyIsNotNullException("应用的appKey不能为空!");
		}
		if(log.isInfoEnabled()) {
			log.info("appKey="+appKey);
		}
		if(!doApplyByAppKeyIsExist(appKey)) {
			throw new AppKeyIsNotExistException("你输入appKey没有对用的应用,请检查");
		}
		if(!doCheckingApplyIsOn(appKey)) {
			throw new ApplyIsNotOnException("当前appKey对应的应用还未上线!");
		}
		if(!isCurreentApply(appKey)) {
			throw new ApplyIsNotCurrentApplyException("当前appKey与接口所属应用不一致!");
		}
		//ApiManage apiManage = apiManageService.selectApiManageAndApiversionIdByApiIdAndVersionStatusAndVerifyStatusAndDeleteStatus(request.getRequestURI().replace("/weather-api", ""));
		ApiManage apiManage = getApiManage(request.getRequestURI().replace("/weather-api", ""),request.getMethod());
		//做认证成功以后的操作
		Map<String, Object> resMap=null;
	    //业务库中的插入操作   以流的方式传递 在验证的时候读取过一次，现在继续读取就没有数据了
		String requestBodyJsonStr = getRequestBodyStr(request);
		//String requestBodyJsonStr=(String) request.getAttribute("requestBodyJsonStr");
		//将requestBody中请求字符串转化为map
		 resMap = SignUtil.convertJsonToMap(requestBodyJsonStr);
		// 去掉签名信息
		// resMap.remove("sign");
		 List<AddField> addFieldList = addFieldService.selectAddFieldListByApiVersionId(apiManage.getApiVersionId());
		 Set<String> addFieldPenNameSet=new HashSet<String>();
		 if(addFieldList!=null) {
			 for (AddField addField : addFieldList) {
				 addFieldPenNameSet.add(addField.getPenName());
			}
			 
		 }
		 Set<String> requestKey = resMap.keySet();
		 if(isSetEqual(addFieldPenNameSet, requestKey)) {
			 DatabaseSource databaseSource = databaseSourceService.getDatabaseSourceDetails(apiManage.getDatabaseSourceId());
			 if(databaseSource==null) {
				 throw new DatabaseSourceIsNullException("接口的数据源为空，请检查配置!");
			 }
			 log.info("数据库中存储的sql:"+apiManage.getSqlTemplet());
			 NamedParameterJdbcTemplate namedParameterJdbcTemplate = NamedParameterJdbcTemplateUtil.getNamedParameterJdbcTemplate(databaseSource.getDatabaseIP(), databaseSource.getPort(), databaseSource.getDatabaseName(), databaseSource.getUserName(), databaseSource.getPassword());
			 //int update = namedParameterJdbcTemplate.update(apiManage.getSqlTemplet().replaceAll(REGEXP, ""), resMap);
			 int update = namedParameterJdbcTemplate.update(apiManage.getSqlTemplet(), resMap);
			 if(update!=0) {
				 log.info("插入成功!");
				 responseResult=new BaseResponse("200","插入成功",null);
			 }
		 }else {
			 log.info("请求参数不匹配,请更正以后再访问!");
			 throw new RequestParamIsNotMatchException("请求参数不匹配,请更正以后再访问!");
		 }
		return responseResult;
		
	}

	private boolean isCurreentApply(String appKey) {
		Apply apply = applyManageService.selectApplyByAppKey(appKey);
		List<ApplyApi> applyApiList = applyManageService.selectCurrentApplyListByAppId(apply.getId());
		if(applyApiList!=null && applyApiList.size()>0) {
			if(applyApiList.get(0).getApplyId().equals(apply.getId())) {
				return true;
			}
			
		}
		return false;
	}

	@Override
	public PageInfo doGetServiceByAppKey(HttpServletRequest request, HttpServletResponse response,ApiManage apiManage ) throws Exception {
		PageInfo page=null;
		String appKey=request.getHeader("appKey");
		if(StringUtils.isEmpty(appKey)){
			appKey= request.getParameter("appKey");
		}
		checkAppkey(appKey);
		//ApiManage apiManage = getApiManage(request.getRequestURI().replace("/weather-api", ""),request.getMethod());
		 if(apiManage.getApiType().equals(SUBJECT)) {
    		 //主题库中的第三方接口
    		 if(apiManage.getIsOutSide().equals(ApiRequestModeStatusEnum.YES.getStatus())) {
    			 //doSubjectOutSideByGet(request,apiManage,response);
    		 }else {
    			 page= doSubjectByGetByAppKey(request,apiManage,response);
    		 }
    		 //业务库
    	 }else {
    		
    		 if(apiManage.getIsOutSide().equals(ApiRequestModeStatusEnum.YES.getStatus())) {
    			//业务库中的第三方接口处理入口 TODO
    			
    		 }else {
    			 page=doBusinessByGetByAppKey(request,apiManage,response);
    			 
    		 }
    	 }
		return page;
	}

	private boolean doCheckPageNoAndPageSize(Integer pageNo, Integer pageSize) {
		if(pageNo<this.pageNo) {
			return false;
		}else if(pageSize>this.pageSize) {
			return false;
			
		}else {
			return true;
		}
	}

	@Override
	public BaseResponse doPutServiceByAppKey(HttpServletRequest request, HttpServletResponse response) throws AppKeyIsNotNullException, AppKeyIsNotExistException, ApplyIsNotOnException, RequestURIErrorException, ApiIsDisableException, ApiIsDeleteException, ApiVersionIsDisableException, ApiVersionIsNotVerifyPassException, ApiVersionIsDeleteException, IOException, DatabaseSourceIsNullException, RequestParamIsNotMatchException, ApplyIsNotCurrentApplyException {
		BaseResponse responseResult=null;
		String appKey=request.getHeader("appKey");
		if(StringUtils.isEmpty(appKey)){
			appKey=  request.getParameter("appKey");
		}
		if(StringUtils.isBlank(appKey)) {
			throw new AppKeyIsNotNullException("接口应用的appKey不能为空!");
		}
		if(log.isInfoEnabled()) {
			log.info("appKey="+appKey);
		}
		if(!doApplyByAppKeyIsExist(appKey)) {
			throw new AppKeyIsNotExistException("你输入appKey没有对用的应用,请检查");
		}
		if(!doCheckingApplyIsOn(appKey)) {
			throw new ApplyIsNotOnException("当前appKey对应的应用还未上线!");
		}
		if(!isCurreentApply(appKey)) {
			throw new ApplyIsNotCurrentApplyException("当前appKey与接口所属应用不一致!");
		}
		//ApiManage apiManage = apiManageService.selectApiManageAndApiversionIdByApiIdAndVersionStatusAndVerifyStatusAndDeleteStatus(request.getRequestURI());
		ApiManage apiManage = getApiManage(request.getRequestURI().replace("/weather-api", ""),request.getMethod());
			//做认证成功以后的操作
		Map<String, Object> resMap=null;
	    //业务库中的插入操作
		//String requestBodyJsonStr = getRequestBodyStr(request);
		//业务库中的插入操作   以流的方式传递 在验证的时候读取过一次，现在继续读取就没有数据了
		String requestBodyJsonStr = getRequestBodyStr(request);
		//String requestBodyJsonStr=(String) request.getAttribute("requestBodyJsonStr");
		//将requestBody中请求字符串转化为map
		 resMap = SignUtil.convertJsonToMap(requestBodyJsonStr);
		// 去掉签名信息
		 //resMap.remove("sign");
		 List<UpdateField> updateFieldList = updateFieldService.selectUpdateFieldListByApiVersionId(apiManage.getApiVersionId());
		 Set<String> updateFieldPenNameSet=new HashSet<String>();
		 for (UpdateField updateField : updateFieldList) {
			 //在实际环境中测试一段时间考虑用不用只取必须字段
			 updateFieldPenNameSet.add(updateField.getPenName());
		}
		 //更新操作更新字段和where条件的key合并之后作比较
		 Set<String> requestParamPenNameSet=new HashSet<String>();
		 List<ApiRequestParam> apiRequestParamList= apiRequestParamService.selectApiRequestParamListByApiVersionId(apiManage.getApiVersionId());
		 for (ApiRequestParam apiRequestParam : apiRequestParamList) {
			 requestParamPenNameSet.add(apiRequestParam.getPenName());
			
		}
		 updateFieldPenNameSet.addAll(requestParamPenNameSet);
		 if(isSetEqual(updateFieldPenNameSet, resMap.keySet())) {
			 DatabaseSource databaseSource = databaseSourceService.getDatabaseSourceDetails(apiManage.getDatabaseSourceId());
			 if(databaseSource==null) {
				 throw new DatabaseSourceIsNullException("接口的数据源为空，请检查配置!");
			 }
			 log.info("数据库中存储的sql:"+apiManage.getSqlTemplet());
			 NamedParameterJdbcTemplate namedParameterJdbcTemplate = NamedParameterJdbcTemplateUtil.getNamedParameterJdbcTemplate(databaseSource.getDatabaseIP(), databaseSource.getPort(), databaseSource.getDatabaseName(), databaseSource.getUserName(), databaseSource.getPassword());
			 //int update = namedParameterJdbcTemplate.update(apiManage.getSqlTemplet().replaceAll(REGEXP, ""), resMap);
			 int update = namedParameterJdbcTemplate.update(apiManage.getSqlTemplet(), resMap);
			 if(update!=0) {
				 log.info("更新成功,一共更新了"+update+"条记录");
				 responseResult=new BaseResponse("200","更新成功,一共更新了"+update+"条记录",null);
			 }else {
				 responseResult=new BaseResponse("700","更新失败,请求条件为:【"+SignUtil.convertMapToJson(resMap)+"】没有匹配的记录,请检查查询条件!",null);
			 }
		 }else {
			 log.info("请求参数不匹配,请更正以后再访问!");
			 throw new RequestParamIsNotMatchException("请求参数不匹配,请更正以后再访问!");
		 }
		return responseResult;
	}

	@Override
	public BaseResponse doDeleteServiceByAppKey(HttpServletRequest request, HttpServletResponse response) throws AppKeyIsNotNullException, AppKeyIsNotExistException, ApplyIsNotOnException, RequestURIErrorException, ApiIsDisableException, ApiIsDeleteException, ApiVersionIsDisableException, ApiVersionIsNotVerifyPassException, ApiVersionIsDeleteException, IOException, DatabaseSourceIsNullException, RequestParamIsNotMatchException, ApplyIsNotCurrentApplyException {
		BaseResponse responseResult=null;
		String appKey=request.getHeader("appKey");
		if(StringUtils.isEmpty(appKey)){
			appKey=request.getParameter("appKey");
		}
		if(StringUtils.isBlank(appKey)) {
			throw new AppKeyIsNotNullException("接口应用的appKey不能为空!");
		}
		if(log.isInfoEnabled()) {
			log.info("appKey="+appKey);
		}
		if(!doApplyByAppKeyIsExist(appKey)) {
			throw new AppKeyIsNotExistException("你输入appKey没有对用的应用,请检查");
		}
		if(!doCheckingApplyIsOn(appKey)) {
			throw new ApplyIsNotOnException("当前appKey对应的应用还未上线!");
		}
		if(!isCurreentApply(appKey)) {
			throw new ApplyIsNotCurrentApplyException("当前appKey与接口所属应用不一致!");
		}
		//ApiManage apiManage = apiManageService.selectApiManageAndApiversionIdByApiIdAndVersionStatusAndVerifyStatusAndDeleteStatus(request.getRequestURI());
		ApiManage apiManage = getApiManage(request.getRequestURI().replace("/weather-api", ""),request.getMethod());
		//做认证成功以后的操作
		Map<String, Object> resMap=null;
	    //业务库中的插入操作
		//String requestBodyJsonStr = getRequestBodyStr(request);
		//业务库中的插入操作   以流的方式传递 在验证的时候读取过一次，现在继续读取就没有数据了
		String requestBodyJsonStr = getRequestBodyStr(request);
		//String requestBodyJsonStr=(String) request.getAttribute("requestBodyJsonStr");
		//将requestBody中请求字符串转化为map
		 resMap = SignUtil.convertJsonToMap(requestBodyJsonStr);
		// 去掉签名信息
		 //resMap.remove("sign");
		 Set<String> requestParamPenNameSet=new HashSet<String>();
		 List<ApiRequestParam> apiRequestParamList= apiRequestParamService.selectApiRequestParamListByApiVersionId(apiManage.getApiVersionId());
		 for (ApiRequestParam apiRequestParam : apiRequestParamList) {
			 requestParamPenNameSet.add(apiRequestParam.getPenName());
		}
		 if(isSetEqual(requestParamPenNameSet, resMap.keySet())) {
			 DatabaseSource databaseSource = databaseSourceService.getDatabaseSourceDetails(apiManage.getDatabaseSourceId());
			 if(databaseSource==null) {
				 throw new DatabaseSourceIsNullException("接口的数据源为空，请检查配置!");
			 }
			 log.info("数据库中存储的sql:"+apiManage.getSqlTemplet());
			 NamedParameterJdbcTemplate namedParameterJdbcTemplate = NamedParameterJdbcTemplateUtil.getNamedParameterJdbcTemplate(databaseSource.getDatabaseIP(), databaseSource.getPort(), databaseSource.getDatabaseName(), databaseSource.getUserName(), databaseSource.getPassword());
			 //int update = namedParameterJdbcTemplate.update(apiManage.getSqlTemplet().replaceAll(REGEXP, ""), resMap);
			 int update = namedParameterJdbcTemplate.update(apiManage.getSqlTemplet(), resMap);
			 if(update!=0) {
				 log.info("删除成功,一共删除了"+update+"条记录");
				 responseResult=new BaseResponse("200","删除成功,一共删除了"+update+"条记录",null);
			 }else {
				 responseResult=new BaseResponse("700","删除失败,请求条件为:【"+SignUtil.convertMapToJson(resMap)+"】没有匹配的记录,请检查查询条件!",null);
			 }
		 }else {
			 log.info("请求参数不匹配,请更正以后再访问!");
			 throw new RequestParamIsNotMatchException("请求参数不匹配,请更正以后再访问!");
		 }
		return responseResult;
	}

	@Override
	public void doGetFileServiceByAppKey(HttpServletRequest request, HttpServletResponse response) throws AppKeyIsNotNullException, AppKeyIsNotExistException, ApplyIsNotOnException, RequestURIErrorException, ApiIsDisableException, ApiIsDeleteException, ApiVersionIsDisableException, ApiVersionIsNotVerifyPassException, ApiVersionIsDeleteException, IOException, ApplyIsNotCurrentApplyException {
		InputStream inputStream=null;
		String appKey=request.getHeader("appKey");
		if(StringUtils.isBlank(appKey)) {
			appKey = request.getParameter("appKey");
			if(StringUtils.isBlank(appKey)) {
				throw new AppKeyIsNotNullException("接口应用的appKey不能为空!");
			}
		}
		if(log.isInfoEnabled()) {
			log.info("appKey="+appKey);
		}
		if(!doApplyByAppKeyIsExist(appKey)) {
			throw new AppKeyIsNotExistException("你输入appKey没有对用的应用,请检查");
		}
		if(!doCheckingApplyIsOn(appKey)) {
			throw new ApplyIsNotOnException("当前appKey对应的应用还未上线,请联系后台管理员...");
		}
		if(!isCurreentApply(appKey)) {
			throw new ApplyIsNotCurrentApplyException("当前appKey与接口所属应用不一致!");
		}
		ApiManage apiManage = getApiManage(request.getRequestURI().replace("/weather-api", ""),request.getMethod());
		 if(apiManage.getApiType().equals(SUBJECT)) {
    		 //主题库中的第三方接口
    		 if(apiManage.getIsOutSide().equals(ApiRequestModeStatusEnum.YES.getStatus())) {
    			 //doSubjectOutSideByGet(request,apiManage,response);
    			 //文件接口
    		 }else {
    			 //主题库中的文件接口
    			 //String expires = request.getHeader("Expires");
    			 //String oSSAccessKeyId = request.getHeader("OSSAccessKeyId");
    			// String signature = request.getHeader("Signature");
    			// if(StringUtils.isEmpty(expires)||StringUtils.isEmpty(oSSAccessKeyId)||StringUtils.isEmpty(signature)) {
    			//	 throw new FileApiExpiresOSSAccessKeyIdSignatureIsNullException("文件接口请求头中Expires或OSSAccessKeyId或Signature不能为空");
    			// }
    			 Map<String, String[]> parameterMap = request.getParameterMap();
    				Map<String, Object> pMap =new HashMap<String,Object>();
    				Set<String> keys= parameterMap.keySet();
    				for (String key : keys) {
    					pMap.put(key, parameterMap.get(key)[0]);
    				}
    				pMap.remove("appKey");
    			 log.info("数据库中存储的OSS路径:"+apiManage.getFileApiPath());
    			 //szmbdata01/radar/radar_png/${date}/${picNum}/ newCAPPI/${picDate}/AWS_GD_CAPPI__3.png_${wj_date}_${wj_cd}_${xh}.png
    			 String ossFilePath = getSimpleOssFilePath(apiManage.getFileApiPath(),pMap);
    			 log.info("OSS路径:"+ossFilePath);
    			 inputStream=HttpClientUtils.sendFileHttpGet(null, ossFilePath, "UTF-8");
    			 OutputStream outputStream = new BufferedOutputStream(response.getOutputStream());
    				//创建存放文件内容的数组
    				byte[] buff =new byte[1024];
    				//所读取的内容使用n来接收
    				int n;
    				//当没有读取完时,继续读取,循环
    				while((n=inputStream.read(buff))!=-1){
    					//将字节数组的数据全部写入到输出缓冲流中
    					outputStream.write(buff,0,n);
    				}
    				//强制将缓存区的数据进行输出
    				outputStream.flush();
    				//关流
    				outputStream.close();
    				inputStream.close();
    		 }
    		 //业务库
    	 }else {
    		
    		 if(apiManage.getIsOutSide().equals(ApiRequestModeStatusEnum.YES.getStatus())) {
    			//业务库中的第三方接口处理入口 TODO
    			
    		 }else{
    			 //业务库中文件接口处理
    			// String expires = request.getHeader("Expires");
    			 //String oSSAccessKeyId = request.getHeader("OSSAccessKeyId");
    			 //String signature = request.getHeader("Signature");
    			 //if(StringUtils.isEmpty(expires)||StringUtils.isEmpty(oSSAccessKeyId)||StringUtils.isEmpty(signature)) {
    			//	 throw new FileApiExpiresOSSAccessKeyIdSignatureIsNullException("文件接口请求头中Expires或OSSAccessKeyId或Signature不能为空");
    			// }
    			 Map<String, String[]> parameterMap = request.getParameterMap();
    				Map<String, Object> pMap =new HashMap<String,Object>();
    				Set<String> keys= parameterMap.keySet();
    				for (String key : keys) {
    					pMap.put(key, parameterMap.get(key)[0]);
    				}
    				pMap.remove("appKey");
    			 log.info("数据库中存储的OSS路径:"+apiManage.getFileApiPath());
    			 String ossFilePath = getSimpleOssFilePath(apiManage.getFileApiPath(),pMap);
    			 log.info("OSS路径:"+ossFilePath);
    			 inputStream= HttpClientUtils.sendFileHttpGet(null, ossFilePath, "UTF-8");
    			 OutputStream outputStream = new BufferedOutputStream(response.getOutputStream());
    				//创建存放文件内容的数组
    				byte[] buff =new byte[1024];
    				//所读取的内容使用n来接收
    				int n;
    				//当没有读取完时,继续读取,循环
    				while((n=inputStream.read(buff))!=-1){
    					//将字节数组的数据全部写入到输出缓冲流中
    					outputStream.write(buff,0,n);
    				}
    				//强制将缓存区的数据进行输出
    				outputStream.flush();
    				//关流
    				outputStream.close();
    				inputStream.close();
    		 }
    	 }
	}

	@Override
	public Object doGetOutSideService(HttpServletRequest request, HttpServletResponse response) throws AppKeyIsNotNullException, AppKeyIsNotExistException, ApplyIsNotOnException, ApplyIsNotCurrentApplyException, RequestURIErrorException, ApiIsDisableException, ApiIsDeleteException, ApiVersionIsDisableException, ApiVersionIsNotVerifyPassException, ApiVersionIsDeleteException {
		String appKey=request.getHeader("appKey");
		if(StringUtils.isBlank(appKey)) {
			appKey=request.getParameter("appKey");
			if(StringUtils.isBlank(appKey)) {
				throw new AppKeyIsNotNullException("接口应用的appKey不能为空!");
			}
		}
		if(log.isInfoEnabled()) {
			log.info("appKey="+appKey);
		}
		if(!doApplyByAppKeyIsExist(appKey)) {
			throw new AppKeyIsNotExistException("你输入appKey没有对用的应用,请检查");
		}
		if(!doCheckingApplyIsOn(appKey)) {
			throw new ApplyIsNotOnException("当前appKey对应的应用还未上线,请联系后台管理员...");
		}
		if(!isCurreentApply(appKey)) {
			throw new ApplyIsNotCurrentApplyException("当前appKey与接口所属应用不一致!");
		} 
		ApiManage apiManage = getApiManage(request.getRequestURI().replace("/weather-api", ""),request.getMethod());
		 log.info(">>>>访问接口的时候apiManage="+JSONObject.toJSONString(apiManage));
		String content = doSubjectOutSideByGet(request,apiManage,response);
		return content;
	}

	@Override
	public void checkAppkey(String appKey) throws AppKeyIsNotNullException, AppKeyIsNotExistException, ApplyIsNotOnException, ApplyIsNotCurrentApplyException {
		if(StringUtils.isBlank(appKey)) {
			throw new AppKeyIsNotNullException("接口应用的appKey不能为空!");
		}
		if(log.isInfoEnabled()) {
			log.info("appKey="+appKey);
		}
		if(!doApplyByAppKeyIsExist(appKey)) {
			throw new AppKeyIsNotExistException("你输入appKey没有对用的应用,请检查");
		}
		if(!doCheckingApplyIsOn(appKey)) {
			throw new ApplyIsNotOnException("当前appKey对应的应用还未上线,请联系后台管理员...");
		}
		if(!isCurreentApply(appKey)) {
			throw new ApplyIsNotCurrentApplyException("当前appKey与接口所属应用不一致!");
		}
	}

	private Object getRedisResult(ApiManage apiManage,DatabaseSource databaseSource,JSONObject jsonParam){
		Object retObj=new Object();
		String redisComdType =apiManage.getRedisComdType();
		String redisComd =apiManage.getRedisComd();
		if(RedisComdType.cacheHash.comdType.equals(redisComdType)){
			if (RedisComdType.hgetAll.comdType.equals(redisComd)){
				retObj=DynamicCacheHash.hgetAll(databaseSource.getDatabaseIP(),databaseSource.getPort(),databaseSource.getPassword(),jsonParam.getString("key"));
			}else
			if (RedisComdType.hkeys.comdType.equals(redisComd)){
				retObj=DynamicCacheHash.hkeys(databaseSource.getDatabaseIP(),databaseSource.getPort(),databaseSource.getPassword(),jsonParam.getString("key"));
			}else
			if (RedisComdType.hmget.comdType.equals(redisComd)){
				String fields = jsonParam.getString("fields");
				if(StringUtils.isNotEmpty(fields)){
					retObj=DynamicCacheHash.hmget(databaseSource.getDatabaseIP(),databaseSource.getPort(),databaseSource.getPassword(),jsonParam.get("key")+"",fields.split(","));
				}
			}else
			if (RedisComdType.hget.comdType.equals(redisComd)){
				retObj=DynamicCacheHash.hget(databaseSource.getDatabaseIP(),databaseSource.getPort(),databaseSource.getPassword(),jsonParam.getString("key"),jsonParam.getString("field"));
			}
		}
		if(RedisComdType.cacheGet.comdType.equals(redisComdType)){
			if (RedisComdType.getValue.comdType.equals(redisComd)){
				retObj=DynamicCacheGet.getValue(databaseSource.getDatabaseIP(),databaseSource.getPort(),databaseSource.getPassword(),jsonParam.getString("key"));
			}else
			if (RedisComdType.getObject.comdType.equals(redisComd)){
				retObj=DynamicCacheGet.getObject(databaseSource.getDatabaseIP(),databaseSource.getPort(),databaseSource.getPassword(),jsonParam.getString("key"));
			}else
			if (RedisComdType.getKeys.comdType.equals(redisComd)){
				retObj=DynamicCacheGet.getKeys(databaseSource.getDatabaseIP(),databaseSource.getPort(),databaseSource.getPassword(),jsonParam.getString("keys"));
			}
		}
		return  retObj;
	}
	//替换自定会议的特殊标签
	private String getReplaTagSqlTemplet(String sqlTemplet,Map<String,Object> pMap){
		String keyVlue="";
		for(String key : pMap.keySet()){
			keyVlue =pMap.get(key)+"";
			sqlTemplet=sqlTemplet.replace("$(:"+key+")",keyVlue);
			sqlTemplet=sqlTemplet.replace("$(in-val=:"+key+")",StringUtils.joinStrings(keyVlue));
			sqlTemplet=sqlTemplet.replace("$(like-left=:"+key+")"," like '%"+keyVlue+"' ");
			sqlTemplet=sqlTemplet.replace("$(like-right=:"+key+")"," like '"+keyVlue+"%' ");
			sqlTemplet=sqlTemplet.replace("$(like-all=:"+key+")"," like '%"+keyVlue+"%' ");
		}
		return  sqlTemplet;
	}

}
